package com.hetang.maijiayun.report.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.hetang.maijiayun.api.inventory.model.InventoryLog;
import com.hetang.maijiayun.api.report.IStockOutInReportService;
import com.hetang.maijiayun.api.report.model.StockOutInReport;
import com.hetang.maijiayun.api.report.model.StockOutInReportDetail;
import com.hetang.maijiayun.api.util.APIException;
import com.hetang.maijiayun.api.util.Constants;
import com.hetang.maijiayun.api.util.JOHelper;
import com.hetang.maijiayun.api.util.Page;
import com.hetang.maijiayun.api.util.PageResultSet;
import com.hetang.maijiayun.api.warehouse.IInventoryLogService;
import com.hetang.maijiayun.report.mappers.StockOutInReportMapper;
import com.hetang.maijiayun.report.utils.CustomerContextHolder;
import com.hetang.maijiayun.utils.security.SecuritySession;

/**
 * 商品销售报表
 * 
 * @author yangfan
 */
@Service("stockOutInReportService")
public class StockOutInReportServiceImpl implements IStockOutInReportService {
	@Autowired
	StockOutInReportMapper stockOutInReportMapper;
	@Autowired
	IInventoryLogService iInventoryLogService;
	
	public static final Logger logger = LoggerFactory.getLogger(StockOutInReportServiceImpl.class);

	public JSONObject fetch(JSONObject param, SecuritySession session) throws APIException {
		logger.info("#stockOutInReport#,param:{}",param);
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_ETL);
		// 验证参数
		dealParam(param,session);
		
		Integer pageNo = param.getInteger("pageNo") == null ? 1 : param.getInteger("pageNo");
		Integer pageSize = param.getInteger("pageSize") == null ? 30 : param.getInteger("pageSize");
		Page page = new Page(pageNo, pageSize);
		// 查询商品总数
		int totalNum = stockOutInReportMapper.countSku(param);
		
		JSONObject result = JOHelper.gen("totalNum", totalNum);
		if (totalNum == 0) {
			result.put("skuStockOutIn", new PageResultSet<JSONObject>());
			return result;
		}
		
		param.put("pageLimitClause", (pageNo - 1) * pageSize + "," + pageSize);
		// 查询每个sku的出入库情况
		List<StockOutInReport> stockInOuts = stockOutInReportMapper.fetch(param);
		//查询每个当前库存数量
//		List<Long> skuIds = new ArrayList<Long>();
//		Map<Long,StockOutInReport> bus = new HashMap<Long,StockOutInReport>();
//		for (StockOutInReport stockOutInReport : stockInOuts) {
//			skuIds.add(stockOutInReport.getSkuId());
//			bus.put(stockOutInReport.getSkuId(), stockOutInReport);
//		}
//		if(CollectionUtils.isNotEmpty(skuIds)){
//			List<WarehouseSku> warehouseSkus = warehouseSkuService.list(JOHelper.gen("skuIds",skuIds,"whId",param.getLong("warehouseId")), session);
//			for (WarehouseSku warehouseSku : warehouseSkus) {
//				StockOutInReport stockOutInReport = bus.get(warehouseSku.getSkuId());
//				stockOutInReport.setQuantity(stockOutInReport.getQuantity()+warehouseSku.getQuantity());
//			}
//		}
		// 查询入库总数量,出库总数量
		JSONObject totalStockOutInNum = stockOutInReportMapper.getTotalStockOutInNum(param);
		
		result.put("skuStockOutIn",
				new PageResultSet<StockOutInReport>(page, totalNum, stockInOuts));
		result.putIfAbsent("totalQuantity", 0);
		result.put("totalSioNum", totalStockOutInNum == null ? 0 : totalStockOutInNum.getIntValue("totalSioNum"));
		result.put("totalSooNum", totalStockOutInNum == null ? 0 : totalStockOutInNum.getIntValue("totalSooNum"));
		return result;
	}

	@Override
	public PageResultSet<StockOutInReportDetail> fetchDetail(JSONObject param, SecuritySession session) throws APIException {
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_ETL);
		Long skuId = param.getLong("skuId");
		//查询出入库明细
		if(Objects.isNull(skuId)){
			throw APIException.builder().illegalArgError().errorMsg("skuId不能为空").build();
		}
		dealParam(param,session);
		//查询总数量
//		Integer totalNum = stockOutInReportMapper.countStockOutInDetail(param);
//		if(totalNum == 0){
//			return new PageResultSet<StockOutInReportDetail>(page, totalNum, new ArrayList<StockOutInReportDetail>());
//		}
//		param.put("pageLimitClause", (pageNo - 1) * pageSize + "," + pageSize);
		PageResultSet<InventoryLog> ps = iInventoryLogService.list(param, session);
		List<StockOutInReportDetail> details = convertStockOutInDetail(ps.getResultSet(),session);
		return new PageResultSet<StockOutInReportDetail>(new Page(param.getInteger("pageNo"), param.getInteger("pageSize")), ps.getTotalItemNum(), details);
	}
	
	private List<StockOutInReportDetail> convertStockOutInDetail(List<InventoryLog> logs,
			SecuritySession session) {
		List<StockOutInReportDetail> result = new ArrayList<StockOutInReportDetail>();
		if(CollectionUtils.isEmpty(logs)){
			return result;
		}
		//计算出入库总价,需要对log加个字段
		for (InventoryLog log : logs) {
			StockOutInReportDetail detail = new StockOutInReportDetail();
			detail.setCode(log.getRelatedCode());
			detail.setCrtTs(log.getCrtTs());
			detail.setRelatedCode(log.getRelatedOriginCode());
			detail.setNum(Math.abs(log.getChgPi()));
			detail.setType(Constants.InventoryLog.relatedTypeMap.get(log.getRelatedType()));
			result.add(detail);
		}
		return result;
	}
	
	private void dealParam(JSONObject param, SecuritySession session) throws APIException{
		try {
			if(Objects.isNull(param)){
				throw APIException.builder().illegalArgError().errorMsg("统计参数不能为空").build();
			}
			String reportDateStartStr = param.getString("reportDateStart");
			String reportDateEndStr = param.getString("reportDateEnd");
			if(StringUtils.isBlank(reportDateStartStr)
					||StringUtils.isBlank(reportDateEndStr)){
				throw APIException.builder().illegalArgError().errorMsg("统计日期不能为空").build();
			}
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date reportDateStart = df.parse(reportDateStartStr);
			Date reportDateEnd = df.parse(reportDateEndStr);
			if(reportDateEnd.getTime()-reportDateStart.getTime()>1000*3600*24*31L){
				throw APIException.builder().illegalArgError().errorMsg("统计日期区间不能超过一个月").build();
			}
			//
			param.putIfAbsent("pageNo", 1);
			param.putIfAbsent("pageSize", 30);
			param.put("tenantryId", session.tenantry.id);
		} catch (ParseException e) {
			throw APIException.builder().illegalArgError().errorMsg("日期格式错误").build();
		}
	}

}
